/*
 Copyright (C) 2009 are of boxtorrents
 boxtorrents, azureus, vuze, and java are copyrighted to their respective owner.

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; version 2 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */
package com.boxtorrents.azureus.action;

import org.gudy.azureus2.plugins.config.ConfigParameter;
import org.gudy.azureus2.plugins.config.ConfigParameterListener;
import org.gudy.azureus2.plugins.download.Download;
import org.gudy.azureus2.plugins.download.DownloadManager;
import org.gudy.azureus2.plugins.download.DownloadManagerListener;
import org.gudy.azureus2.plugins.logging.LoggerChannel;
import org.gudy.azureus2.plugins.ui.config.StringListParameter;

import com.boxtorrents.azureus.PluginParamConstants;
import com.boxtorrents.azureus.StatCheckEvent;
import com.boxtorrents.azureus.StatCheckListener;
import com.boxtorrents.azureus.BoxTorrentsPlugin;
import com.boxtorrents.azureus.Util;

/**
 * Pause when reach danger ratio
 * 
 * @author are of boxtorrents
 */
public class PauseDownloadAction implements StatCheckListener,
    DownloadManagerListener {
	private static final long serialVersionUID = 6062758009950570179L;
	private static final LoggerChannel log = BoxTorrentsPlugin.getLog();
	private int last = -1;
	private static boolean actenable = false;

	/**
	 * Create new
	 */
	public PauseDownloadAction() {
		BoxTorrentsPlugin.getPluginInterface().getPluginconfig()
		    .getPluginParameter(PluginParamConstants.PR_DOWNLOAD_HANDLER)
		    .addConfigParameterListener(new ConfigParameterListener() {
			    public void configParameterChanged(ConfigParameter cnf) {
				    if (cnf instanceof StringListParameter) {
					    StringListParameter par = (StringListParameter)cnf;
					    actenable = par.getValue().equals("pause");
					    onEnabled(actenable);
				    }
			    }
		    });
		if (isEnabled()) onEnabled(true);
	}

	private void onDangerCheck(StatCheckEvent e) {
		// pausing all boxtorrent downloads
		int count = doBoxtorrentsPause(e.getPluginInterface().getDownloadManager()
		    .getDownloads());
		if (count > 0) {
			if (isAlertEnable()) {
				log.logAlert(LoggerChannel.LT_WARNING, "pausing " + count
				    + " boxtorrents download(s)\n" + e.toString());
			} else {
				log.log(LoggerChannel.LT_INFORMATION, "successuffy pausing " + count
				    + " boxtorrents download(s)");
			}
		}
	}

	private void onNormalCheck(StatCheckEvent e) {
		// resuming all boxtorrent downloads
		int count = doBoxtorrentsResume(e.getPluginInterface().getDownloadManager()
		    .getDownloads());
		if (count > 0) {
			if (isAlertEnable()) {
				log.logAlert(LoggerChannel.LT_INFORMATION, "resuming " + count
				    + " paused boxtorrents downloads\n" + e.toString());
			} else {
				log.log(LoggerChannel.LT_INFORMATION, "successuffy resuming " + count
				    + " paused boxtorrents downloads");
			}
		}
	}

	private int doBoxtorrentsResume(Download[] downloads) {
		int count = 0;
		for (Download dwl : downloads) {
			if (!dwl.isComplete() && dwl.isPaused()
			    && Util.isBoxtorrentsDownload(dwl)) {
				dwl.resume();
				count++;
				log.log(LoggerChannel.LT_INFORMATION, "resuming: " + dwl.getName());
			}
		}
		return count;
	}

	private int doBoxtorrentsPause(Download[] downloads) {
		int count = 0;
		for (Download dwl : downloads) {
			if (!dwl.isComplete() && Util.isBoxtorrentsDownload(dwl)
			    && !dwl.isPaused()) {
				dwl.pause();
				count++;
				log.log(LoggerChannel.LT_INFORMATION, "pausing: " + dwl.getName());
			}
		}
		return count;
	}

	/**
	 * @inheritDoc
	 */
	public boolean isEnabled() {
		return actenable;
	}

	private boolean isAlertEnable() {
		return BoxTorrentsPlugin.getPluginInterface().getPluginconfig()
		    .getPluginBooleanParameter(
		        PluginParamConstants.PR_DOWNLOAD_HANDLER_ALERT, false);
	}

	/**
	 * @inheritDoc
	 */
	public void onCheckResult(StatCheckEvent e) {
		if (e.getEventType() == StatCheckEvent.EVENT_DANGER) {
			onDangerCheck(e);
		} else if (e.getEventType() == StatCheckEvent.EVENT_NORMAL) {
			onNormalCheck(e);
		}
		last = e.getEventType();
	}

	/**
	 * @inheritDoc
	 */
	public void onEnabled(boolean enabled) {
		final DownloadManager downloadManager = BoxTorrentsPlugin
		    .getPluginInterface().getDownloadManager();
		if (!enabled) {
			last = -1;
			downloadManager.removeListener(this);
		} else {
			downloadManager.addListener(this);
		}
	}

	/**
	 * @inheritDoc
	 */
	public void downloadAdded(Download download) {
		if (last == StatCheckEvent.EVENT_DANGER && isEnabled()
		    && Util.isBoxtorrentsDownload(download)) {
			int i = doBoxtorrentsPause(new Download[] { download });
			if (i > 0 && isAlertEnable())
			  log.logAlert(LoggerChannel.LT_WARNING, "pausing " + download.getName());
		}
	}

	/**
	 * @inheritDoc
	 */
	public void downloadRemoved(Download arg0) {}
}
